package com.gai.shop.web.controller;

import cn.dsna.util.images.ValidateCode;
import com.gai.shop.common.Const;
import com.gai.shop.util.StrUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CodeController extends BaseController {
    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            ValidateCode vc = new ValidateCode(120,30,4,20);
            //获取生成的验证码
            String code = vc.getCode();
            //把验证码保存到session
            request.getSession().setAttribute(Const.VALIDATE,code);
            vc.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String checkCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端输入的验证码
        String code = request.getParameter("code");
        //获取session中保存的验证码
        String validate = (String)request.getSession().getAttribute(Const.VALIDATE);
        String result = "1";
        if (StrUtils.empty(code)){
            //验证码有值的，验证码2遍是否相同
            if (validate.equalsIgnoreCase(code)){
                result = "0";
            }
        }
        return result;
    }
}
